package zpy.servlet.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import zpy.servlet.pojo.Student;

import java.io.IOException;

public class LoginServlet extends HttpServlet {

	ServletConfig config;
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config = config;
		ServletContext application = getApplication();
		application.setAttribute("wen", "天王盖地虎");
		application.setAttribute("da", "宝塔镇河妖");
		config.getInitParameter("debug");
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return this.config;
	}

	public ServletContext getApplication() {
		return config.getServletContext();
	}

	/**
	 * 处理HTTP请求的服务方法
	 * 
	 * @param req HttpServletRequest对象，包含客户端的请求信息
	 * @param res HttpServletResponse对象，用于向客户端发送响应
	 * @throws ServletException 当Servlet处理发生错误时抛出
	 * @throws IOException 当输入输出操作发生错误时抛出
	 */
	@Override
	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String option = req.getParameter("option");
		if (option !=null) {
			// 如果option参数存在，使当前会话失效并转发到登录页面
			HttpSession session = req.getSession(false);
			if (session != null) {
				session.invalidate();
			}
			req.getRequestDispatcher("/login.jsp").forward(req, res);
		}else{
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			HttpSession session = req.getSession();
			Student student = new Student();
			student.setName(username);
			session.setAttribute("student", student);
			// 登录成功后转发到主页面
			req.getServletContext().getRequestDispatcher("/public/main.jsp")
			.forward(req, res);
		}
		
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
